package com.zhixue.study.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhixue.exception.ZhixuePlusException;
import com.zhixue.message.model.po.MqMessage;
import com.zhixue.message.service.MqMessageService;
import com.zhixue.study.config.PayNotifyConfig;
import com.zhixue.study.mapper.XcLearnRecordMapper;
import com.zhixue.study.model.po.XcLearnRecord;
import com.zhixue.study.service.*;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther: 李 力
 * @Date: 2025/5/15
 * @Description: com.zhixue.study.service.impl
 * @version: 1.0
 */
@Service
public class LearnRecordServiceImpl extends ServiceImpl<XcLearnRecordMapper, XcLearnRecord> implements LearnRecordService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    MqMessageService mqMessageService;

    @Autowired
    MyCourseTablesService myCourseTablesService;

    @RabbitListener(queues = PayNotifyConfig.PAYNOTIFY_QUEUE)
    public void receive(Message message) {
        //获取消息
        MqMessage mqMessage = JSON.parseObject(message.getBody(), MqMessage.class);
        //消息类型
        String messageType = mqMessage.getMessageType();
        //订单类型,60201表示购买课程
        String businessKey2 = mqMessage.getBusinessKey2();
        //这里只处理支付结果通知
        if (PayNotifyConfig.MESSAGE_TYPE.equals(messageType) && "60201".equals(businessKey2)) {
            //选课记录id
            String choosecourseId = mqMessage.getBusinessKey1();
            //添加选课
            boolean b = myCourseTablesService.saveChooseCourseStauts(choosecourseId);
            if (!b) {
                //添加选课失败，抛出异常，消息重回队列
                throw new ZhixuePlusException("收到支付结果，添加选课失败");
            }
        }
    }
}
